<?php
namespace GK;
class Request
{
    /*键值检查
    $Type:获取键值接收格式
    $Value:接收键值名称
    */
    public static function Has($Type='Get',$Value=''){
        switch(strtoupper($Type)){
            case 'GET':
                if(!empty($Value)&&isset($_GET[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'POST':
                if(!empty($Value)&&isset($_POST[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'REQUEST':
                if(!empty($Value)&&isset($_REQUEST[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'ENV':
                if(!empty($Value)&&isset($_ENV[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'COOKIE':
                if(!empty($Value)&&isset($_COOKIE[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'SESSION':
                if(!empty($Value)&&isset($_SESSION[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'SERVER':
                if(!empty($Value)&&isset($_SERVER[$Value])){
                    return true;
                }else{
                    return false;
                }
            break;
            case 'GLOBALS':
                if (!empty($Value)&&isset($GLOBALS[$Value])) {
                    return true;
                }else{
                    return false;
                }
            break;
            case 'FILES':
                if (!empty($Value)&&isset($_FILES[$Value])) {
                    return true;
                }else{
                    return false;
                }
            break;
            case 'URL':
                ini_set('max_execution_time',5);
                if(!empty($Value)){
                    $ch = curl_init();
                    $timeout = 3;
                    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                    curl_setopt($ch, CURLOPT_HEADER, 1);
                    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                    curl_setopt($ch,CURLOPT_URL,$Value);
                    curl_exec($ch);
                    return $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
                    curl_close($ch);
                }else{
                    return '404';
                }
            break;
            default:
                return false;
        }
    }
    //参数过滤
    public static function filterWords(&$str)
    {
        $farr = array(
            "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
            "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
            "/select\b|insert\b|update\b|delete\b|drop\b|;|\"|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
        );
        $str = preg_replace($farr,'',$str);
        $str = strip_tags($str);
        return $str;
    }
    public static function post($value='')
    {
        if (empty($value))
        {
            return $_POST;
        }
        if (self::has('POST',$value))
        {
            return self::filterwords($_POST[$value]);
        }
        else
        {
            return false;
        }
    }
    public static function get($value='')
    {
        if (empty($value))
        {
            return $_GET;
        }
        if (self::has('GET',$value))
        {
            return self::filterwords($_GET[$value]);
        }
        else
        {
            return false;
        }
    }
    public static function request($value='')
    {
        if (empty($value))
        {
            return $_REQUEST;
        }

        if (self::has('REQUEST',$value))
        {
            return $_REQUEST[$value];
        }
        else
        {
            return false;
        }
    }
    public static function env($value='')
    {
        if (empty($value))
        {
            return $_ENV;
        }

        if (self::has('ENV',$value))
        {
            return $_ENV[$value];
        }
        else
        {
            return false;
        }
    }
    public static function session($value='')
    {
        if (empty($value))
        {
            return $_SESSION;
        }

        if (self::has('SESSION',$value))
        {
            return $_SESSION[$value];
        }
        else
        {
            return false;
        }
    }
    public static function server($value='')
    {
        if (empty($value))
        {
            return $_SERVER;
        }

        if (self::has('SERVER',$value))
        {
            return $_SERVER[$value];
        }
        else
        {
            return false;
        }
    }
    public static function cookie($value='')
    {
        if (empty($value))
        {
            return $_COOKIE;
        }

        if (self::has('COOKIE',$value))
        {
            return $_COOKIE[$value];
        }
        else
        {
            return false;
        }
    }
    public static function globals($value='')
    {
        if (empty($value))
        {
            return $GLOBALS;
        }

        if (self::has('GLOBALS',$value))
        {
            return $GLOBALS[$value];
        }
        else
        {
            return false;
        }
    }
    public static function files($value='')
    {
        if (empty($value))
        {
            return $_FILES;
        }

        if (self::has('FILES',$value))
        {
            return $_FILES[$value];
        }
        else
        {
            return false;
        }
    }

    
    public static function header($name = '')
    {
        $header = [];
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) 
        {
            $header = $result;
        }else{
            foreach ($_SERVER as $key => $val) 
            {
                if (0 === strpos($key, 'HTTP_')) 
                {
                    $key= str_replace('_', '-', strtolower(substr($key, 5)));
                    $header[$key] = $val;
                }
            }
            if (isset($_SERVER['CONTENT_TYPE'])) 
            {
                $header['content-type'] = $_SERVER['CONTENT_TYPE'];
            }
            if (isset($_SERVER['CONTENT_LENGTH'])) 
            {
                $header['content-length'] = $_SERVER['CONTENT_LENGTH'];
            }
        }
        $resp = array_change_key_case($header);
        if (is_array($name)) 
        {
            return $resp = array_merge($resp, $name);
        }
        if ('' === $name) 
        {
            return $resp;
        }
        $name = str_replace('_', '-', strtolower($name));
        return isset($resp[$name]) ? $resp[$name] : null;
    }
    //数组核对
    public static function CheckData_Array($Sgin=[],$Data=[]){
        if(empty($Sgin)&&empty($Data)){
            return false;
        }else{
            $error=array();
            foreach($Data as $key => $value) {
                $Data_key=$Sgin[$key];
                if($value!=$Data_key){
                    $error[]='数据错误参数:'.$key;
                }
            }
            if(empty($error)){
                return true;
            }else{
                return false;
            }
        }
    }
    public static function GetIP(){
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
            $ip = getenv('HTTP_CLIENT_IP');
        }elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        $res=preg_match('/[\d\.]{7,15}/',$ip,$matches)?$matches[0]:null;
        if(empty($res)){
            return self::GetOnlineIP();
        }else{
            return $res;
        }
    }
    //网络IP获取
    public static function GetOnlineIP(){
        $Curl=new \GK\Curl();
        $result=$Curl->R('http://2019.ip138.com/ic.asp');
        if($result){
            preg_match('/(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/',$result,$res);
            return $res[0];
        }else{
            return '未知IP地址';
        }
    }
    //获取浏览器信息
    public static function GetBroswer(){
        $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
        if (stripos($sys, "Firefox/") > 0) {
            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
            $exp[0] = "Firefox";
            $exp[1] = $b[1];  //获取火狐浏览器的版本号
        } elseif (stripos($sys, "Maxthon") > 0) {
            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
            $exp[0] = "傲游";
            $exp[1] = $aoyou[1];
        } elseif (stripos($sys, "MSIE") > 0) {
            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
            $exp[0] = "IE";
            $exp[1] = $ie[1];  //获取IE的版本号
        } elseif (stripos($sys, "OPR") > 0) {
                preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
            $exp[0] = "Opera";
            $exp[1] = $opera[1];  
        } elseif(stripos($sys, "Edge") > 0) {
            //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
            $exp[0] = "Edge";
            $exp[1] = $Edge[1];
        } elseif (stripos($sys, "Chrome") > 0) {
                preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
            $exp[0] = "Chrome";
            $exp[1] = $google[1];  //获取google chrome的版本号
        } elseif(stripos($sys,'rv:')>0 && stripos($sys,'Gecko')>0){
            preg_match("/rv:([\d\.]+)/", $sys, $IE);
                $exp[0] = "IE";
            $exp[1] = $IE[1];
        }else {
           $exp[0] = "未知浏览器";
           $exp[1] = ""; 
        }
        return $exp[0].'('.$exp[1].')';
    }
    /**
     * 检测是否使用手机访问
     * @access public
     * @return bool
     */
    public function isMobile()
    {
        if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
            return true;
        } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
            return true;
        } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
            return true;
        } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 当前是否Ajax请求
     * @access public
     * @param bool $ajax true 获取原始ajax请求
     * @return bool
     */
    public function isAjax($ajax = false)
    {
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
            return true;
        }else{
            return false;
        }
    }
}